<template>
  <div class="menu-manage" v-loading="loading">
    <!-- 添加按钮 -->
    <div class="btn-box">
      <el-button
        v-if="$getAuth('permission:add')"
        type="primary"
        size="small"
        @click="showMenuForm()"
        icon="el-icon-plus"
        >添加菜单</el-button
      >
    </div>

    <!-- 菜单列表 -->
    <div v-if="menuList.length > 0" class="main-table">
      <el-table
        :data="menuList"
        border
        row-key="id"
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"
      >
        <el-table-column prop="menuName" label="菜单名称"></el-table-column>
        <el-table-column prop="path" label="路由路径"></el-table-column>
        <el-table-column prop="name" label="路由名称"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row, $index }">
            <div class="btn-opers">
              <template v-if="$getAuth('permission:add')">
                <el-link
                  :underline="false"
                  v-if="row.parentId === '0'"
                  type="primary"
                  size="mini"
                  @click="addMenu(row, $index)"
                  >添加</el-link
                >
              </template>
              <template v-if="$getAuth('menu:auth')">
                <el-link
                  :underline="false"
                  v-if="row.parentId !== '0'"
                  type="warning"
                  size="mini"
                  @click="showAuth(row, $index)"
                  >权限</el-link
                >
              </template>
              <el-link
                :underline="false"
                v-if="$getAuth('permission:edit')"
                size="mini"
                @click="editMenu(row, $index)"
                >编辑</el-link
              >
              <el-link
                :underline="false"
                v-if="$getAuth('permission:remove')"
                type="danger"
                size="mini"
                @click="removeMenu(row, $index)"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加菜单弹框 -->
    <el-dialog
      title="添加菜单"
      :visible.sync="addMenuShow"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="routerForm"
        :rules="rules"
        ref="routerForm"
        label-width="100px"
      >
        <!-- <el-form-item label="父级名称" prop="parentName">
          <el-input v-model="routerForm.parentName"></el-input>
        </el-form-item> -->
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="routerForm.menuName"></el-input>
        </el-form-item>
        <el-form-item label="路由路径" prop="url">
          <el-input v-model="routerForm.url"></el-input>
        </el-form-item>
        <el-form-item label="路由名称" prop="name">
          <el-input v-model="routerForm.name"></el-input>
        </el-form-item>
        <el-form-item label="菜单排序" prop="sortNo">
          <el-input v-model="routerForm.sortNo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddMenu()" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmAddMenu()" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 菜单页面里的权限 -->
    <auth-btn
      ref="authBtn"
      :title="authTitle"
      :visible.sync="authVisible"
    ></auth-btn>
  </div>
</template>

<script>
import { menuManage } from '@/api'
import authBtn from './authBtn.vue'

export default {
  name: 'menuManage',
  components: { authBtn },
  data() {
    return {
      loading: false, // 加载页面开关
      menuList: [],
      addMenuShow: false, // 控制弹框显示
      // 表单输入数据
      routerForm: {
        menuName: '',
        url: '',
        name: '',
        menuType: 0,
        delFlag: 0,
        sortNo: 0
      },
      // 编辑时临时存的数据
      editRouterForm: null,
      rules: {
        menuName: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        url: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '此项不能为空', trigger: 'blur' }]
      },
      authTitle: '',
      authVisible: false
    }
  },

  created() {
    this.getMenuList()
  },

  mounted() {},

  methods: {
    // 获取路由导航菜单
    async getMenuList() {
      this.loading = true
      try {
        const res = await menuManage.treeByUser(localStorage.getItem('userId'))
        // 删除hasChildren属性，保证树形table正常渲染
        res.data.forEach(d => {
          delete d.hasChildren
          d.children.forEach(c => {
            delete c.hasChildren
          })
        })
        this.menuList = res.data
        this.loading = false
      } catch {
        this.loading = false
      }
    },

    // 点击添加菜单
    showMenuForm(menuType = 0) {
      this.addMenuShow = true
      this.routerForm = {
        menuName: '',
        url: '',
        name: '',
        delFlag: 0,
        sortNo: 0
      }
      this.routerForm.menuType = menuType // 0为一级菜单, 1为二级菜单
    },

    // 添加二级菜单
    addMenu(data, index) {
      this.showMenuForm(1)
      this.routerForm.parentId = data.id
    },

    // 确认添加菜单
    async confirmAddMenu() {
      this.$refs['routerForm'].validate(valid => {
        if (!valid) return false

        const isEdit = this.routerForm.id
        console.log(this.routerForm)
        // return false
        // 有id为编辑，没有为添加
        this.loading = true // 请求加载页面
        try {
          !isEdit
            ? menuManage.insert(this.routerForm).then(res => {
                this.$message.success('添加成功')
                this.getMenuList()
              })
            : menuManage.update(this.routerForm).then(res => {
                this.$message.success('编辑成功')
                this.getMenuList()
              })
        } catch {
          this.loading = false
        }

        this.addMenuShow = false
      })
    },

    // 编辑菜单
    editMenu(data, i) {
      // 父级id为 '0' 则编辑的是一级，否则是二级
      const num = data.parentId === '0' ? 0 : 1
      this.showMenuForm(num)
      this.routerForm.id = data.id
      this.routerForm.menuName = data.menuName
      this.routerForm.url = data.path
      this.routerForm.name = data.name
      if (data.parentId !== '0') {
        this.routerForm.parentId = data.parentId
      }
    },

    // 删除菜单
    async removeMenu(data, index) {
      console.log(data)
      const i = index
      try {
        const btn = await this.$confirm('确定删除此菜单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true
        await menuManage.deleteById(data.id)
        this.$message.success('已删除')
        this.getMenuList()
      } catch {
        console.info('取消删除')
      }
    },

    // 取消表单输入
    cancelAddMenu() {
      this.addMenuShow = false
    },

    // show菜单权限列表
    showAuth(data, index) {
      this.authTitle = data.menuName
      this.authVisible = true
      this.$refs.authBtn.getAuthBtnList(data)
      this.$refs.authBtn.setData(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-manage {
  .main-table {
    margin-top: 12px;
  }
}
</style>
